package com.wenjiang.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wenjiang.common.lang.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理授权异常 权限不足
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {



    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // 告诉浏览器 要用utf-8 进行解析 否则中文乱码
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        ObjectMapper objectMapper= new ObjectMapper();

        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(Result.fail("权限不足")));
    }
}
